package com.ucode.application.controller.oss;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ucode.oss.model.FileInfo;
import com.ucode.oss.service.FileInfoService;
import com.ucode.springboot.starter.fileStorage.FsClient;
import com.ucode.springboot.starter.fileStorage.FsProviderType;
import com.ucode.springboot.starter.fileStorage.UploadResult;
import com.ucode.springboot.ueditor.baidu.ActionEnter;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.ResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.tool.util.IdentifyUtils;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags="文件存储")
@RestController
@RequestMapping("/oss-file")
public class OssController {
    
    @Autowired
    private FileInfoService fileInfoService;
    @Autowired
    private ActionEnter actionEnter;

    private static Log log = LogFactory.get();
    
    @ApiOperation(value="阿里云oss上传成功回调")
    @PostMapping(value ="/aliyun/callback")
    public ResponseResult<Object> callback(HttpServletRequest request){
        String autorizationInput = new String(request.getHeader("Authorization"));
        int contentLen = Integer.parseInt(request.getHeader("content-length"));
        try {
            InputStream is = request.getInputStream();
            byte[] message = new byte[contentLen];
            int readLen = 0;
            int readLengthThisTime = 0;
            while (readLen != contentLen) {
                readLengthThisTime = is.read(message, readLen, contentLen - readLen);
                if (readLengthThisTime == -1) {// Should not happen.
                    break;
                }
                readLen += readLengthThisTime;
            }
            String ossCallbackBody = new String(message);
            
            log.info("autorizationInput==>>"+autorizationInput);
            
            log.info("ossCallbackBody==>>"+ossCallbackBody);
            
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        
        return ResponseResult.success();
    }
    
    
    /**
     * 文件上传
     * 根据fileType选择上传方式
     *
     * @param file
     * @return
     * @throws Exception
     */
    @ApiOperation(value="文件上传")
    @PostMapping(value ="/upload" ,consumes="multipart/*", headers = "content-type=multipart/form-data")
    public ResponseResult<Object> upload(@ApiParam(value="请选择文件",type="__file",required=true) @RequestParam(value ="file",required=true) MultipartFile file) throws Exception {
        
        String originalFilename = file.getOriginalFilename();
        if (!originalFilename.contains(".")) 
            throw new UcodeServiceException(ResultCodeEnum.FILE_MISSING_SUFFIX);
        
        FsProviderType fsProviderType = FsProviderType.qiniu;
        String clientId = "1";
        
        FileInfo fileInfo = new FileInfo();
        fileInfo.setId(IdentifyUtils.getDefaultSnowflakeId());
        fileInfo.setSourceName(originalFilename);
        fileInfo.setMimeType(file.getContentType());
        fileInfo.setIsImg(fileInfo.getMimeType().startsWith("image/"));
        fileInfo.setSize(file.getSize());
        fileInfo.setSource(fsProviderType.name());
        try {
            UploadResult uploadResult = FsClient.getClient(fsProviderType,clientId).upload(fileInfo.getId().toString(),file.getInputStream(),fileInfo.getMimeType());
            if(uploadResult == null){
                return ResponseResult.failed();
            }
            fileInfo.setBucket(uploadResult.getBucket());
            fileInfo.setClientId(uploadResult.getClientId());
            fileInfo.setFilePath(uploadResult.getFilePath());
            fileInfo.setIsPrivate(uploadResult.getIsPrivate());
            fileInfo.setUrlprefix(uploadResult.getUrlprefix());
            int i = fileInfoService.insert(fileInfo);
            return i > 0 ? ResponseResult.success(fileInfo) : ResponseResult.failed();
        } catch (Exception e) {
            log.error(e);
            throw new UcodeServiceException(ResultCodeEnum.SERVER_ERROR);
        }
    }

    
    /**
     * ueditor编辑器统一上传
     * @date 2019年6月17日
     * @param request
     * @return
     */
    @RequestMapping("/ueditor/exec")
    public String ueditorExe(HttpServletRequest request){
        String  sessionId = request.getParameter("Authorization");
        return actionEnter.exec(request);
    }
    
}
